package com.yaojiaxun.logisticsPlatformSystem.service;

import com.baomidou.mybatisplus.plugins.Page;
import com.yaojiaxun.logisticsPlatformSystem.dto.CarInformationDTO;
import com.yaojiaxun.logisticsPlatformSystem.dto.PageDTO;
import com.yaojiaxun.logisticsPlatformSystem.entity.CarInformation;
import com.yaojiaxun.logisticsPlatformSystem.mapper.AreaMapper;
import com.yaojiaxun.logisticsPlatformSystem.mapper.CarInformationMapper;
import com.yaojiaxun.logisticsPlatformSystem.util.TimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Auther: yjx_j
 * @Date: 2019/1/15 13:01
 * @Description:
 */
@Service
public class CarInformationService {

    @Autowired
    private CarInformationMapper carInformationMapper;
    @Autowired
    private AreaMapper areaMapper;

    public void addCar(CarInformation carInformation){
        carInformationMapper.addCarInformation(carInformation);
    }

    public void deleteCar(Integer carId){
        carInformationMapper.deleteCarById(carId);
    }

    //bean对象传入DTO
    public CarInformationDTO beanToDTO(CarInformation carInformation){
        if (carInformation == null)
            return null;
        CarInformationDTO carInformationDTO = new CarInformationDTO();
        BeanUtils.copyProperties(carInformation, carInformationDTO);
        carInformationDTO.setUpdateTime(TimeFormat.convertTime(carInformation.getUpdateTime()));
        carInformationDTO.setCreateTime(TimeFormat.convertTime(carInformation.getCreateTime()));
        return carInformationDTO;
    }

    //分页查询所有车辆信息
    public PageDTO<CarInformationDTO> findPage(Integer pageNum){
        PageDTO<CarInformationDTO> pageDTO = new PageDTO<>();
        Page<CarInformationDTO> page = new Page<>(pageNum, 10);
        List<CarInformationDTO> results = carInformationMapper.selectPage(page, null).stream().map(this::beanToDTO).collect(Collectors.toList());
        pageDTO.setResult(results);
        pageDTO.setPage(page);
        return pageDTO;
    }

    public Boolean updateCarByCarId(CarInformation carInformation){
        carInformation.setUpdateTime(Instant.now().toEpochMilli());
        return carInformationMapper.updateCarByCarId(carInformation) > 0;
    }

    public CarInformation findCarByCarId(Integer carId){
        return carInformationMapper.findCarByCarId(carId);
    }

    public Boolean addCarInformation(CarInformation carInformation){
        carInformation.setCreateTime(Instant.now().toEpochMilli());
        carInformation.setUpdateTime(Instant.now().toEpochMilli());
        return carInformationMapper.addCarInformation(carInformation)>0;
    }

    public CarInformation findCarByCarNumber(String carNumber){
        return carInformationMapper.findCarByCarNumber(carNumber);
    }
}
